#include "resfile.h"

#include <QDebug>
#include <QDataStream>
#include <QMessageBox>
#include <QDataStream>
#include <QTimer>
#include <QSettings>

#include "downloadtool.h"
#include "logger.h"
#include "mydirtools.h"


ResFile::ResFile()
{

}

ResFile::ResFile(QDataStream &data)
{
    setData(data);
}

void ResFile::setData(QDataStream &data)
{
    // name
    int8_t nameSize;
    data >> nameSize;
    char* nameChar = new char[nameSize+1]{0};
    data.readRawData(nameChar,nameSize);
    Name = nameChar;

    // md5
    int32_t count;
    data >> count;
    char* Md5Char = new char[count]{0};
    data.readRawData(Md5Char,count);
    Md5 = QByteArray(Md5Char,count);

    // size
    data >> Size;


}

void ResFileMgr::downloadBin()
{
    QString url = "http://soft.pwidc.cn:8016/PC_ClientVersions/Versions.bin";
//    QString url = config.value("binAddress").toString();
    auto down = new DownloadTool(url,".");
    connect(down,&DownloadTool::sigDownloadFinished,[=](){
        QTimer::singleShot(100,[=](){
            QFileInfo f("Versions.bin");
            if(f.exists() && f.size()>0){
                emit sigBinDownload();
            }
        });
    });

    down->startDownloadToDir();
//    LOG << QString("下载%1成功").arg(url);
}

bool ResFileMgr::loadFile(const QString &path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        // 处理打开文件失败的情况
        qDebug()<<"打开失败";
        LOG<<QString("打开%1失败").arg(path);
//        QMessageBox::about(nullptr,"文件打开失败",path);
        return false;
    }

    QDataStream out(&file);
    out.setByteOrder(QDataStream::LittleEndian);

    out>>Version;
    out>>count;

    for(int i = 0;i<count;i++){
        auto fileInfo = ResFile(out);
        append(fileInfo);
        qDebug()<<"index"<<i<<"name"<<fileInfo.Name;
    }
    if(count > 0){
        LOG<<QString("读取%1成功,共%2项").arg(path).arg(count);
    }

    qDebug()<<"count"<<count;
    return count>0;
}

bool ResFileMgr::loadFormLocalDir(const QString &dirPath)
{
    MyDirTools tool;
    auto paths = tool.getAllFilesInDirectory(dirPath);

    int i =0;
    for(auto filePath : paths){
        ResFile rFile;
        rFile.Name =filePath.mid(dirPath.count()+1);
        rFile.Size = QFileInfo (filePath).size();
        rFile.Md5 = calculateFileMd5(filePath);
        append(rFile);
        LOG<<QString("检查文件更新 %1").arg(rFile.Name);
        if(i%10 == 0){
            QCoreApplication::processEvents();
        }
        i++;
        qDebug()<<"name"<<rFile.Name<<"size"<<rFile.Size<<"md5"<<rFile.Md5.toHex();
    }

    return true;

}

void ResFileMgr::append(const ResFile &file)
{
    resList.insert(file.Name,file);
    TotalBytesCount += file.Size;
}

const QMap<QString, ResFile> &ResFileMgr::getResList() const
{
    return resList;
}

qint64 ResFileMgr::getTotalBytesCount()
{
    return TotalBytesCount;
}

void ResFileMgr::setResList(const QMap<QString, ResFile> &newResList)
{
    resList = newResList;
}

QByteArray ResFileMgr::calculateFileMd5(const QString &filePath) {
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file:" << filePath;
        return "";
    }

    QCryptographicHash hash(QCryptographicHash::Md5);
    if (file.isOpen()) {
        QByteArray data = file.readAll();
        hash.addData(data);
        file.close();
    }

    return hash.result();
//    QByteArray md5 = hash.result();
//    // 将MD5转换为16进制表示的字符串
//    QString md5Hex = md5.toHex();
//    return md5Hex;
}
